using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using DynamicData;
using FluentAvalonia.UI.Controls;
using FluentAvalonia.UI.Navigation;
using FluentAvalonia.UI.Windowing;
using LiftHub.Pages;
using LiftHub.ViewModels.Pages;

namespace LiftHub.Views;

public partial class MainView : UserControl
{

    private string[] StackString => new[]
    {
        "Home", "Weather", "Calendar",
        "Notes", "Ledger", "Setting",
        "Help", "Weekly"
    };

    private PageModelBase[] StackModel => new PageModelBase[]
    {
        new HomePageModel(),new WeatherPageModel(),new CalendarPageModel(),
        new NotesPageModel(),new LedgerPageModel(),new SettingPageModel(),
        new HelpPageModel(),new WeeklyPageModel()
    };

    public MainView()
    {
        InitializeComponent();
    }

    #region Init

    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        FrameView.IsNavigationStackEnabled = true;
        FrameView.NavigationPageFactory = new NavigationFactory();
        Navigate("Home");
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);

        if (VisualRoot is AppWindow aw)
            TitleBarHost.ColumnDefinitions[3].Width = new GridLength(aw.TitleBar.RightInset, GridUnitType.Pixel);
    }

    #endregion


    private void ItemInvoked(object? sender, NavigationViewItemInvokedEventArgs e)
    {
        if (e.InvokedItemContainer.Tag is not string s) return;
        if (string.IsNullOrEmpty(s)) return;
        Navigate(s);
    }

    public void Navigate(string page)
    {
        var index = StackString.IndexOf(page);
        if(index > -1 && index < StackModel.Length)
            Navigate(StackModel[index]);
    }

    public void Navigate(object context)
    {
        if (FrameView.Content is PageView pageView) pageView.PageClosing();
        FrameView.NavigateFromObject(context, new FrameNavigationOptions());
    }

    private void OnBackRequested(object? sender, NavigationViewBackRequestedEventArgs e)
    {
        if (FrameView.Content is PageView view) view.PageClosing();
        FrameView.GoBack();
    }

    private void BackClick(object? sender, RoutedEventArgs e)
    {
        if (FrameView.Content is PageView view) view.PageClosing();
        FrameView.GoBack();
    }
}